#include <material_editor/shadereditor.h>
#include <session.h>

ShaderEditor::ShaderEditor(Shader* shader, QWidget *parent)
  : BaseMaterialEditorWidget(parent)
	, _shader(0)
{
	_editor = new GLSLTextEditor(this);
  _groupView = new GroupTreeItemView(this);

  connect (_editor, SIGNAL(ContentChanged()), this, SLOT(ContentChanged ()));

  QGridLayout* layout = new QGridLayout (this);
  layout->addWidget(_groupView, 0, 0, 1, 1);
  layout->addWidget(_editor, 1, 0, 1, 1);

  if (shader)
    {
      SetShader(shader);
    }
}


void ShaderEditor::UpdateGUI()
{
	if (_shader)
		{
			_editor->document()->setPlainText(_shader->GetCode());
		}
}


void ShaderEditor::SetShader(Shader *shader)
{
  _shader = shader;
  _groupView->SetGroupTreeItem(&shader->GetCategory());


  SetItem (shader);
	UpdateGUI();
  SetDirty (false);
}

void ShaderEditor::SetLine(int line)
{
  _editor->SetCursorToLine(line);
}

Shader* ShaderEditor::GetShader () 
{
  return _shader;
}


void ShaderEditor::ContentChanged ()
{
  SetDirty(true);
}

void ShaderEditor::Save ()
{
  _shader->SetCode(_editor->document()->toPlainText());
  _shader->Save();
  SetDirty(false);
}

void ShaderEditor::Compile()
{
  Save ();
  iShader* shader = _shader->GetShader();


  if (shader->Compile())
    {
      printf ("Compile: OK\n");
    }

  std::string log = shader->GetCompileInfoLog();
  printf ("Compile-Log: %s\n", log.c_str());
  fflush(stdout);
}
